/**
 * Created by yx on 2017/7/12.
 */
// var $tbody = $("#sample-table-1 tbody");
// jQuery(function ($) {
//     $('.date-picker').datepicker({autoclose: true}).next().on(ace.click_event, function () {
//         $(this).prev().focus();
//     });
// });
var allStation = [];
var nowdate = new Date();
var oneweekdate = new Date(nowdate-7*24*3600*1000);
// $("#startdate").val(beginDate(oneweekdate));
// $("#enddate").val(endDate(nowdate));

function beginDate(date) {
    return endDate(date);
};

function endDate(date) {
    return date.getFullYear() + "-" + ("0" + (date.getMonth() + 1)).slice(-2) + "-" + ("0" + date.getDate()).slice(-2);
};
console.log("signManage");
// getAllInfo().done(function() {
// 初始化table
$("#sign_table").bootstrapTable({
    // 'url': '../serviceType/findAll',
    'url': '/community/forumMessageLabel/getSearcherForummessagelabel',
    'toolbar': $('div[data-name="btnCtl"]'),
    'queryParams': queryParams,
    'cache':false,
    'sidePagination': 'server',
    'toolbarAlign': 'right',
    'undefinedText': '-',
    'striped': true,
    'pagination': true,
    'sortable': true, //是否启用排序
    'sortOrder': "asc", //排序方式
    'pageSize': globalPageSize,
    'pageList': [],
    'clickToSelect': true,
    'singleSelect': true,
    'smartDisplay': true,
    'ajaxOptions':{
        headers: {"Authorization": localStorage.token}
    },
    'responseHandler': function (resb) {
        return {
            'total': resb.data.total,
            'rows': resb.data.rows
        }
    },
    'onCheck': function() {
        $("button[data-target='#commentModal'], button[data-target='#deleteModal']").removeAttr("disabled");
    },
    'onUncheck': function() {
        $("button[data-target='#commentModal'], button[data-target='#deleteModal']").attr("disabled", 'true');
    },
    'onPageChange': function() {
        if($("#sign_table").bootstrapTable('getSelections')[0]){
            $("#sign_table").bootstrapTable('uncheckBy', {
                field: 'typeId',
                values: [$("#sign_table").bootstrapTable('getSelections')[0].typeId]
            });
        }

    },
    'columns': [{
        'checkbox': true,
        'class': 'hide'
    },
        {
            title: '序号',
            'align': 'center',
            formatter: function (value, row, index) {
                return index+1;
            }
        },{
            'field': 'forumMessageLabelId',
            'title': '标签ID',
            'width':100,
            'align': 'center',
            'class': 'hide labelId'
        },{
            'field': 'labelDescribe',
            'title': '标签内容',
            'align': 'center'
        },{
            'field': 'orderNo',
            'title': '显示顺序',
            'width':100,
            'align': 'center'
        },{
            'field': 'createDate',
            'title': '创建日期',
            'width':150,
            'align': 'center'
        },{
            'field': 'labelStatus',
            'title': '标签状态',
            'width':100,
            'align': 'center',
            'formatter': function (labelStatus) {
                var obj = {'0':'显示','1':'隐藏'};
                var html = "<button class='btn btn-sm btn-success labToggleShow'>"+obj[labelStatus]+"</button>";
                return html;
            }
        }

    ]
});
// });

//请求服务数据时所传参数
function queryParams(params){
    return {
        // 'labelDescribe': $('#desc').val(),
        // 'labelStatus' : $('#signStatus').val(),
        // 'createDateS': $('#startdate').val(),
        // 'createDateE' : $('#enddate').val(),
        limit : params.limit, //每一页的数据行数，默认是上面设置的10(pageSize)
        offset : params.offset/params.limit+1 //当前页面,默认是上面设置的1(pageNumber)
    }
}

/**
 * 标签查询查询ajax
 * @param name 请求查询的服务人员名称
 */
function signQuery() {
    if($("#desc").val() === '' && $(".selectClassify").val() === ''){
        $('#sign_table').bootstrapTable('refreshOptions',{pageNumber:1,pageSize:globalPageSize});
    }else{
        $.ajaxSetup({cache:false});
        $.ajax({
            type: "GET",
            // url: "/community/forummessage/getFindMsg",
            url: "/community/forumMessageLabel/getSearcherForummessagelabel?labelDescribe="+$('#desc').val()+"&labelStatus="+$('#signStatus').val()+"&limit="+globalPageSize+"&offset=1",
            // data: {
            //     "msgContent": $('#contentName').val(),
            //     'msgType': $('.selectClassify').val(),
            //     'createDateS': $('#startdate').val(),
            //     'createDateE': $('#enddate').val()
            // },
            dataType: 'json',
            // contentType: "application/json",
            beforeSend: function (request) {
                request.setRequestHeader("Authorization", localStorage.token);
            },
            success: function(resb) {
                console.log(resb);
                if (resb.data.length != 0) {
                    $("#sign_table").bootstrapTable('load', {
                        'total': resb.data.total,
                        'rows': resb.data.rows
                    });
                } else {
                    $("#sign_table").bootstrapTable('removeAll');
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
    }
    return false;
}




/**
 * 列表操作(新增，更新，删除)
 * @param action [add/update/remove]
 * @param data
 *               [add/update 数据结构 {name: string, description: string, listAuthorityId: array} ]
 *               [delete 数据结构 {roleId: int}]
 * @param async/scync [default async]
 */
function SignManagement(action, data, async) {
    var url = null;
    (async === false) ? async = false: async = true;
    if (action === 'add') {
        url = '/community/forumMessageLabel/saveForumMessageLabel?'+objTostring(data);
    } else {
        url = '/community/forumMessageLabel/deleteForumMessageLabel?'+objTostring(data);
    };
    return $.ajax({
        type: "GET",
        url: url,
        // data: JSON.stringify(data),
        contentType: "application/json",
        dataType: 'json',
        beforeSend: function (request) {
            request.setRequestHeader("Authorization", localStorage.token);
        },
        async: async,
        success: function(resb) {
            alert(resb.message);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            // console.log(XMLHttpRequest, textStatus, errorThrown);
            alert(textStatus);
        }
    });
}

function objTostring(obj) {
    var arr = [];
    for(var i in obj) {
        arr.push(i+"="+obj[i]);
    }
    console.log(arr.join('&'))
    return arr.join('&');
}

$(document).on('click','.spanIcons',function(){
    $('#inputStation').val("");
    if($('#inputStation').val() ==""){
        $('.spanIcons').removeClass('glyphicon glyphicon-remove');
    }
});

//切换显示与隐藏
$("#sign_table").on('click', '.labToggleShow', function () {
    console.log($(this).parent().parent().find('.labelId').html());
    var that = $(this);
    var url = '';
    if(that[0].innerHTML=== '显示') {
        url = '/community/forumMessageLabel/deleteForumMessageLabel?labelId='+$(this).parent().parent().find('.labelId').html()
    }else {
        url = '/community/forumMessageLabel/recoveryForumMessageLabel?labelId='+$(this).parent().parent().find('.labelId').html()
    };
    $.ajaxSetup({cache:false});
    $.ajax({
        url: url,
        type: "GET",
        contentType: "application/json",
        dataType: 'json',
        success: function(resb) {
            if(resb.success) {
                that[0].innerHTML = that[0].innerHTML === "隐藏" ? "显示" : '隐藏';
            }else {
                alert("修改失败");
            }
        },
        error: function(err) {
            alert(err);
        }
    });
});

$("#inputStation").keyup(function(){
    if($('#inputStation').val() !=""){
        $('.spanIcons').addClass('glyphicon glyphicon-remove');
    }
    if($('#inputStation').val() ==""){
        $('.spanIcons').removeClass('glyphicon glyphicon-remove');
    }
});


/**
 * 查询表单提交
 */
$("#dataSearch").on('click',function() {
    return signQuery();
});

$("#selectClassify").change(function () {
    return signQuery();
});

//$("#stationFormId").submit(function() {
//    return yuanfenQueryByStationId($("#serviceProviderSel").val());
//});

/**
 * 新增模态框显示
 */
$("#addModal").on('show.bs.modal', function() {
    $(this).find("input[type=text]").val("");
});

/**
 * 删除模态框显示
 */
// $("#deleteModal").on('show.bs.modal', function() {
//     // var name = $("#sign_table").bootstrapTable('getSelections')[0].name,
//     var html = '是否删除?';
//     $(this).find('div.modal-body').empty().append(html);
// });

/**
 * 评论模态框显示
 */

$("#commentModal").on('show.bs.modal', function() {
    var forumMsgId = $("#sign_table").bootstrapTable('getSelections')[0].forumMsgId;
    getComment(forumMsgId);
});

/**
 * 新增,更新,删除角色表单提交
 */
$("button[name=submit]").on('click',function() {
    var type = $(this).data("type"),
        $modal = $("#" + type + "Modal"),
        $inputs = $modal.find('input[type="text"]'),
        $selects = $modal.find('select')


    //$checkboxs = $(this).find('input[type="checkbox"]').prop('checked',true),
    tableData = $("#sign_table").bootstrapTable("getSelections")[0],
        data = null,
        $that = $(this);


    // 模式选择,设置不同的data和url
    if (type === 'delete') {
        data = {
            'labelId': tableData.forumMessageLabelId
        };
    } else if (type === 'add') {
        var obj = $("#addForm").validationEngine('validate', {
            promptPosition: "centerRight",
            autoPositionUpdate: true,
            scroll: false,
            validationEventTrigger:'blur',
            autoHidePrompt: true,
            autoHideDelay: 3000,
            binded:true,
            showOneMessage:true
        });
        if (!obj) {
            return false;
        };
        // var $status = $modal.find('select[name="status"]');
        // var $orderNo = $modal.find('select[name="orderNo"]');
        data = {
            'labelDescribe': $('#addDesc').val(),
            'labelStatus': $('#addLableStatus').val()
        };
    } else if (type ==='update') {
        var $status = $modal.find('select[name="status"]');

        data = {
            'typeId':$inputs[0].value,
            'name':$inputs[1].value,
            'introduction': $inputs[2].value,
            'distributionCosts': $inputs[3].value,
            'status':$status.val()

        };
        data['typeId'] = tableData.typeId;
    };


    $modal.modal('hide');
    // 完成ajax后刷新表格数据
    SignManagement(type, data).done(function() {
        $("#sign_table").bootstrapTable("refresh");
        $("button[data-target='#updateModal'], button[data-target='#deleteModal']").attr("disabled", 'true');
        $that.parents('.modal-content').find('form')[0].reset();
    });

    // 阻止表格冒泡事件
    return false;
});
